# 导入模块
# 禁用警告
import numpy as np
import pandas as pd
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
import warnings
warnings.filterwarnings('ignore')


df = pd.read_excel('./dealedDate.xls')
x_col_list = ['A' + str(x) for x in range(1, 21)]
X = df[x_col_list].values
y = df['Class'].values

# 生成随机数据


def makeRandomData():

    from random import shuffle as sf
    global X, y
    # y=dp(y_ori)
    list_is_0 = []
    list_not_0 = []
    for _x, _y in enumerate(y):
        if _y == 0:
            list_is_0.append(_x)
        else:
            list_not_0.append(_x)
    assert len(list_is_0) == 700 and len(list_not_0) == 300
    # list_0_bat=dp(list_is_0)
    # list_not_0_bat=dp(list_not_0)
    sf(list_is_0)
    sf(list_not_0)
    # print(list_is_0[:10],list_not_0[:10])
    tr_list = list_is_0[:560] + list_not_0[:240]
    test_list = list_is_0[560:] + list_not_0[240:]
    x_train_list = [X[_x] for _x in tr_list]
    y_train_list = [y[_x] for _x in tr_list]
    x_test = [X[_x] for _x in test_list]
    y_test = [y[_x] for _x in test_list]
    # print(len(set(tr_list+test_list)),len(x_train_list),len(x_test))
    assert len(set(tr_list + test_list)
               ) == 1000 and len(x_train_list) == 800 and len(x_test) == 200
    return [x_train_list, y_train_list, x_test, y_test]

# 进行函数拟合


def doJob(X_train, y_train, X_test, y_test):

    ss = StandardScaler()
    X_train = ss.fit_transform(X_train)
    X_test = ss.transform(X_test)
    lr = LogisticRegression()
    # 调用逻辑斯蒂回归，使用fit函数训练模型参数
    lr.fit(X_train, y_train)
    # 进行数据预测
    lr_y_predict = lr.predict(X_test)
    # 统计匹配率
    result_rate = lr.score(X_test, y_test)
    #print('The rate is %.8s' % (result_rate))
    return result_rate


def main(count=1):

    dict_result = {}
    for _x in range(count):
        dict_result[_x] = doJob(*makeRandomData())
    result = list({_x: dict_result[_x]} for _x in list(
        sorted(dict_result, key=lambda x: dict_result[x])))
    # print(result)
    print('=' * 90)
    for x in range(count):
        print('第%d次:%.3f' % (x + 1, dict_result[x]), end=' ')
        if (x + 1) % 5 == 0 and x != 0:
            print('前%d次的平均匹配率为：%.3f' %
                  (x + 1, sum(list(dict_result.values())[:x + 1]) / (x + 1)))
        if (x + 1) % 5 == 0:
            print('=' * 90)
    print('\n')
    print(('The average rate is %.3f' %
           (sum(list(dict_result.values())) / count)).center(90, '='))


if __name__ == '__main__':
    main(100)
